import { constantRoutes} from '@/router'
import { asyncRoutes } from '@/router/router-backend.js'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta) {
    return roles.some(role => route.path==role.uri)
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
export function mapAsyncRoutes (routers, data) {
  formatSecondRoutes(routers, data)
}
export function formatSecondRoutes (routers, data) {
  data.forEach(route => {
    let menu = {
      path: route.uri,
      alwaysShow: true,
      component: () => import('@/layout'),
      meta: { title: route.name,icon: route.icon}
    }
    if (route.children && route.children.length>0) {
      menu.children = []
      formatThirdRoutes(menu.children, route.children)
    }
    routers.push(menu)
  })
}
export function formatThirdRoutes (thirdRouters, routes) {
  routes.forEach(route => {
    if (asyncRoutes[route.uri] && asyncRoutes[route.uri].routes) {
      const allroutes = asyncRoutes[route.uri].routes
      allroutes.forEach(ele => {
        let menu = {
          path: ele.path,
          component: ele.component,
          hidden: ele.hidden,
          name: route.name,
          meta: { title: route.name, icon: route.icon,removeTagsView: ele.meta ? ele.meta.removeTagsView ? ele.meta.removeTagsView : false : false}
        }
        if (ele.hidden) {
          menu.name = ele.title
          menu.meta = { title: ele.title, icon: route.icon,activeMenu: ele.activeMenu, removeTagsView: ele.meta ? ele.meta.removeTagsView ? ele.meta.removeTagsView : false : false}
        }
        thirdRouters.push(menu)
      })
    }
  })
}
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  CLEAR_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = []
  },
}

const actions = {
  generateRoutes({ commit }, roles) {
    
    return new Promise(resolve => {
      let accessedRoutes = []
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
        
        // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      mapAsyncRoutes(accessedRoutes, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  clearRoutes({ commit }) {
    commit('CLEAR_ROUTES')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
